﻿using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

using AjaxControlToolkit;

[assembly: WebResource("SCS.Web.UI.WebControls.Dialogs.MessageBoxControl.js", "text/javascript")]
[assembly: WebResource("SCS.Web.UI.WebControls.Dialogs.MessageBoxControl.debug.js", "text/javascript")]

[assembly: WebResource("SCS.Web.UI.WebControls.Dialogs.none.gif", "image/gif")]
[assembly: WebResource("SCS.Web.UI.WebControls.Dialogs.error.gif", "image/gif")]
[assembly: WebResource("SCS.Web.UI.WebControls.Dialogs.info.gif", "image/gif")]
[assembly: WebResource("SCS.Web.UI.WebControls.Dialogs.warning.gif", "image/gif")]
[assembly: WebResource("SCS.Web.UI.WebControls.Dialogs.question.gif", "image/gif")]

namespace SCS.Web.UI.WebControls.Dialogs
{
    [RequiredScript(typeof(Dialog), 1)]    
    [ClientScriptResource("SCS.MessageBox", "SCS.Web.UI.WebControls.Dialogs.MessageBoxControl.js", LoadOrder = 2)]
    [RequiredScript(typeof(ConfirmButtonExtender), 3)]

    public class MessageBox : Dialog
    {
        #region Fields

        private HtmlInputButton _button1;
        private HtmlInputButton _button2;
        private HtmlInputButton _button3;

        #endregion

        public virtual void Show(string title, string text, MessageBoxButtons buttons)
        {
            Show(title, text, buttons, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
        }
        public virtual void Show(string title, string text, MessageBoxButtons buttons, MessageBoxIcon icon)
        {
            Show(title, text, buttons, icon, MessageBoxDefaultButton.Button1);
        }
        public virtual void Show(string title, string text, MessageBoxButtons buttons, MessageBoxIcon icon, MessageBoxDefaultButton defaultButton)
        {
            Text = text;
            Buttons = buttons;
            Icon = icon;
            DefaultButton = defaultButton;

            base.Show(title, text);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            _button1.EnableViewState =  PostBack;
            _button2.EnableViewState = PostBack;
            _button3.EnableViewState = PostBack;

            if (!PostBack)
            {
                _button1.ServerClick -= new EventHandler(_button1_Click);
                _button2.ServerClick -= new EventHandler(_button2_Click);
                _button3.ServerClick -= new EventHandler(_button3_Click);
            }

            if (ConfirmMode)
            {
                // Register an empty OnSubmit statement so the ASP.NET WebForm_OnSubmit method will be automatically
                // created and our behavior will be able to wrap it if necessary
                ToolkitScriptManager.RegisterOnSubmitStatement(this, typeof(ConfirmButtonExtender), "ConfirmButtonExtenderOnSubmit", "null;");

                PostBackScript = Page.ClientScript.GetPostBackEventReference(FindPageControl(TargetControlId), "");
            }
        }

        protected override void Render(HtmlTextWriter writer)
        {
            switch (Buttons)
            {
                case MessageBoxButtons.OK:

                    _button1.Value = "OK";
                    _button2.Style[HtmlTextWriterStyle.Display] = "none";
                    _button3.Style[HtmlTextWriterStyle.Display] = "none";
                    break;

                case MessageBoxButtons.OKCancel:

                    _button1.Value = "OK";
                    _button2.Value = "Cancel";
                    _button3.Style[HtmlTextWriterStyle.Display] = "none";
                    break;

                case MessageBoxButtons.YesNo:

                    _button1.Value = "Yes";
                    _button2.Value = "No";
                    _button3.Style[HtmlTextWriterStyle.Display] = "none";
                    break;

                case MessageBoxButtons.YesNoCancel:

                    _button1.Value = "Yes";
                    _button2.Value = "No";
                    _button3.Value = "Cancel";
                    break;
            }

            base.Render(writer);
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            _button1 = new HtmlInputButton();
            _button1.ID = "button1";
            _button1.CausesValidation = false;
            _button1.ServerClick += new EventHandler(_button1_Click);

            _button2 = new HtmlInputButton();
            _button2.ID = "button2";
            _button2.CausesValidation = false;
            _button2.ServerClick += new EventHandler(_button2_Click);

            _button3 = new HtmlInputButton();
            _button3.ID = "button3";
            _button3.CausesValidation = false;
            _button3.ServerClick += new EventHandler(_button3_Click);

            Controls.Add(_button1);
            Controls.Add(_button2);
            Controls.Add(_button3);
        }

        protected override void RenderDialogContent(HtmlTextWriter writer)
        {
            // write icon in left side div
            //
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "icon");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            // write icon image tag
            writer.AddAttribute(HtmlTextWriterAttribute.Alt, GetIconResourceAltText(Icon));
            //writer.AddAttribute(HtmlTextWriterAttribute.Src, Page.ClientScript.GetWebResourceUrl(this.GetType(), GetIconResourceName(Icon)));
            writer.RenderBeginTag(HtmlTextWriterTag.Img);
            writer.RenderEndTag(); // close img tag

            writer.RenderEndTag(); // close image's div tag

            // write content text to right of image icon
            //
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "text");
            writer.RenderBeginTag(HtmlTextWriterTag.Span);
            writer.Write(Text);            
            writer.RenderEndTag(); // close content text's div tag

            // render buttons on their only line
            //
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "buttons");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);

            _button1.RenderControl(writer);
            _button2.RenderControl(writer);
            _button3.RenderControl(writer);

            writer.RenderEndTag(); // close button div tag            
        }

        protected override void LoadClientState(string clientState)
        {
            base.LoadClientState(clientState);

            if (ClientStateCollection.ContainsKey("buttonNumber"))
            {
                int number = (int)ClientStateCollection["buttonNumber"];

                if (number > 0)
                {
                    SetDialogResult(number);
                    OnButtonClicked(this, new CommandEventArgs("", number));
                }
            }

            if (ClientStateCollection.ContainsKey("show"))
                ClientStateCollection["show"] = false;
        }

        protected override string SaveClientState()
        {
            return base.SaveClientState();
        }

        protected override List<object> GetAdditionalShowArguments()
        {
            List<object> list = new List<object>();
            list.Add(((int)Buttons));
            list.Add(((int)Icon));
            list.Add(((int)DefaultButton));
            list.Add(RedirectUrl);

            return list;
        }

        #region Event Stuff

        protected void _button1_Click(object sender, EventArgs e)
        {
            OnButtonClicked(sender, e);
        }
        protected void _button2_Click(object sender, EventArgs e)
        {
            OnButtonClicked(sender, e);
        }
        protected void _button3_Click(object sender, EventArgs e)
        {
            OnButtonClicked(sender, e);
        }

        private static readonly object _eventSubmitKey = new object();

        [Category("Action"), Description("Raised when the user clicks a button.")]
        public event EventHandler ButtonClicked
        {
            add
            {
                Events.AddHandler(_eventSubmitKey, value);
            }
            remove
            {
                Events.RemoveHandler(_eventSubmitKey, value);
            }
        }

        protected virtual void OnButtonClicked(object sender, EventArgs e)
        {
            EventHandler handler = (EventHandler)Events[_eventSubmitKey];

            int buttonNum = 1;

            if (!(sender is HtmlInputButton))
                return;

            string id = ((HtmlInputButton)sender).ID;

            buttonNum = int.Parse(id.Substring(id.Length - 1));

            SetDialogResult(buttonNum);

            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }

        #endregion

        protected virtual void SetDialogResult(int selectedButtonNumber)
        {
            switch (Buttons)
            {
                case MessageBoxButtons.OK:
                    Result = DialogResult.OK;
                    break;

                case MessageBoxButtons.OKCancel:

                    if (selectedButtonNumber == 1)
                    {
                        Result = DialogResult.OK;
                    }
                    else
                    {
                        Result = DialogResult.Cancel;
                    }
                    break;

                case MessageBoxButtons.YesNo:

                    if (selectedButtonNumber == 1)
                    {
                        Result = DialogResult.Yes;
                    }
                    else
                    {
                        Result = DialogResult.No;
                    }
                    break;

                case MessageBoxButtons.YesNoCancel:

                    if (selectedButtonNumber == 1)
                    {
                        Result = DialogResult.Yes;
                    }
                    else if (selectedButtonNumber == 2)
                    {
                        Result = DialogResult.No;
                    }
                    else
                    {
                        Result = DialogResult.Cancel;
                    }
                    break;
            }
        }

        protected virtual string GetIconResourceName(MessageBoxIcon icon)
        {
            string path = "SCS.Web.UI.WebControls.Dialogs.";

            switch (icon)
            {
                case MessageBoxIcon.Information:
                    path += "info.gif";
                    break;

                case MessageBoxIcon.Error:
                    path += "error.gif";
                    break;

                case MessageBoxIcon.Warning:
                    path += "warning.gif";
                    break;

                case MessageBoxIcon.Question:
                    path += "question.gif";
                    break;

                default:
                    path += "none.gif";
                    break;
            }

            return path;
        }

        protected virtual string GetIconResourceAltText(MessageBoxIcon icon)
        {
            string altText = " ";

            switch (icon)
            {
                case MessageBoxIcon.Information:
                    altText = "Information";
                    break;

                case MessageBoxIcon.Error:
                    altText = "Error";
                    break;

                case MessageBoxIcon.Warning:
                    altText = "Warning";
                    break;

                case MessageBoxIcon.Question:
                    altText = "Question";
                    break;
            }

            return altText;
        }

        private MessageBoxIconsUrls GetIcons()
        {
            return new MessageBoxIconsUrls
                {
                    Error = (ErrorIconImage != null) ? Page.ResolveClientUrl(ErrorIconImage) : Page.ClientScript.GetWebResourceUrl(this.GetType(), GetIconResourceName(MessageBoxIcon.Error)),
                    Info = (InformationIconImage != null) ? Page.ResolveClientUrl(InformationIconImage) : Page.ClientScript.GetWebResourceUrl(this.GetType(), GetIconResourceName(MessageBoxIcon.Information)),
                    Question = (QuestionIconImage != null) ? Page.ResolveClientUrl(QuestionIconImage) : Page.ClientScript.GetWebResourceUrl(this.GetType(), GetIconResourceName(MessageBoxIcon.Question)),
                    Warn = (WarningIconImage != null) ? Page.ResolveClientUrl(WarningIconImage) : Page.ClientScript.GetWebResourceUrl(this.GetType(), GetIconResourceName(MessageBoxIcon.Warning))
                };
        }

        #region Properties

        [ExtenderControlProperty(true, true)]
        [Browsable(true), DefaultValue(""), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual MessageBoxIconsUrls IconUrls
        {
            get
            {
                return GetIcons();
            }
        }

        [ExtenderControlProperty]
        [Browsable(true), DefaultValue(false), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public bool PostBack
        {
            get
            {
                object o = ViewState["PostBack"];
                return (o != null) ? (bool)o : false;
            }
            set
            {
                ViewState["PostBack"] = value;
            }
        }

        [ExtenderControlProperty]        
        [Browsable(true), DefaultValue(false), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public bool ConfirmMode
        {
            get
            {
                object o = ViewState["ConfirmMode"];
                return (o != null) ? (bool)o : false;
            }
            set
            {
                ViewState["ConfirmMode"] = value;
            }
        }

        [Browsable(true), DefaultValue(""), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual string Text
        {
            get
            {
                object o = ViewState["text"];

                if (o != null)
                    return (string)o;

                return "";
            }
            set
            {
                ViewState["text"] = value;
            }
        }

        [Browsable(true), DefaultValue(""), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual string Caption
        {
            get
            {
                EnsureChildControls();
                return Title;
            }
            set
            {
                EnsureChildControls();
                Title = value;
            }
        }

        [Browsable(true), DefaultValue(false), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public override bool ShowCloseButton
        {
            get
            {
                return false;
            }
            set
            {
                base.ShowCloseButton = false;
            }
        }

        [ExtenderControlProperty]
        [Browsable(true), DefaultValue(MessageBoxButtons.OK), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual MessageBoxButtons Buttons
        {
            get
            {
                object o = ViewState["Buttons"];

                if (o != null)
                    return (MessageBoxButtons)o;

                return MessageBoxButtons.OK;
            }
            set
            {
                ViewState["Buttons"] = value;
            }
        }

        [ExtenderControlProperty]
        [Browsable(true), DefaultValue(MessageBoxIcon.None), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual MessageBoxIcon Icon
        {
            get
            {
                object o = ViewState["Icon"];

                if (o != null)
                    return (MessageBoxIcon)o;

                return MessageBoxIcon.None;
            }
            set
            {
                ViewState["Icon"] = value;
            }
        }

        [ExtenderControlProperty]
        [Browsable(true), DefaultValue(MessageBoxDefaultButton.Button1), Bindable(false), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual MessageBoxDefaultButton DefaultButton
        {
            get
            {
                object o = ViewState["DefaultButton"];

                if (o != null)
                    return (MessageBoxDefaultButton)o;

                return MessageBoxDefaultButton.Button1;
            }
            set
            {
                ViewState["DefaultButton"] = value;
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public override string Content
        {
            get
            {
                return base.Content;
            }
            set
            {
                base.Content = value;
            }
        }

        [Browsable(false), DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        [DefaultValue(DialogResult.None), Bindable(false), Themeable(false)]
        public DialogResult Result
        {
            get
            {
                object o = ViewState["DefaultButton"];

                if (o != null)
                    return (DialogResult)o;

                return DialogResult.None;
            }
            protected set
            {
                ViewState["DefaultButton"] = value;
            }
        }

        [ExtenderControlProperty]
        [Browsable(true), DefaultValue(""), Bindable(true), Themeable(false)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual string RedirectUrl
        {
            get
            {
                object o = ViewState["RedirectUrl"];

                if (o != null)
                    return (string)o;

                return "";
            }
            set
            {
                ViewState["RedirectUrl"] = value;
            }
        }
                
        [UrlProperty]
        [EditorAttribute(typeof(System.Web.UI.Design.UrlEditor), typeof(System.Drawing.Design.UITypeEditor))]
        [Browsable(true), DefaultValue(""), Bindable(true), Themeable(true)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual string ErrorIconImage
        {
            get
            {
                object o = ViewState["ErrorIconUrl"];
                return (o != null) ? (string)o : null;
            }
            set
            {
                ViewState["ErrorIconUrl"] = value;
            }
        }

        [UrlProperty]
        [EditorAttribute(typeof(System.Web.UI.Design.UrlEditor), typeof(System.Drawing.Design.UITypeEditor))]
        [Browsable(true), DefaultValue(""), Bindable(true), Themeable(true)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual string WarningIconImage
        {
            get
            {
                object o = ViewState["WarningIconUrl"];
                return (o != null) ? (string)o : null;
            }
            set
            {
                ViewState["WarningIconUrl"] = value;
            }
        }

        [UrlProperty]
        [EditorAttribute(typeof(System.Web.UI.Design.UrlEditor), typeof(System.Drawing.Design.UITypeEditor))]
        [Browsable(true), DefaultValue(""), Bindable(true), Themeable(true)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual string InformationIconImage
        {
            get
            {
                object o = ViewState["InfoIconUrl"];
                return (o != null) ? (string)o : null;
            }
            set
            {
                ViewState["InfoIconUrl"] = value;
            }
        }

        [UrlProperty]
        [EditorAttribute(typeof(System.Web.UI.Design.UrlEditor), typeof(System.Drawing.Design.UITypeEditor))]
        [Browsable(true), DefaultValue(""), Bindable(true), Themeable(true)]
        [PersistenceMode(PersistenceMode.Attribute), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), NotifyParentProperty(true)]
        public virtual string QuestionIconImage
        {
            get
            {
                object o = ViewState["QuestionIconUrl"];
                return (o != null) ? (string)o : null;
            }
            set
            {
                ViewState["QuestionIconUrl"] = value;
            }
        }

        [ExtenderControlProperty]
        [ClientPropertyName("postBackScript")]
        [DefaultValue("")]
        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public string PostBackScript
        {
            get;
            private set;
        }

        protected virtual HtmlInputButton Button1
        {
            get
            {
                return _button1;
            }
        }
        protected virtual HtmlInputButton Button2
        {
            get
            {
                return _button2;
            }
        }
        protected virtual HtmlInputButton Button3
        {
            get
            {
                return _button3;
            }
        }

        #endregion
    }
}
